package initialize

import (
	"GinBlog/docs"
	"GinBlog/middleware"
	"GinBlog/router"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

func Routers() *gin.Engine {
	Router := gin.New()

	//使用gin logger
	// LoggerWithFormatter 中间件会写入日志到 gin.DefaultWriter
	// 默认 gin.DefaultWriter = os.Stdout
	Router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		// 你的自定义格式
		return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
	}))
	Router.Use(gin.Logger())

	Router.Use(gin.Recovery())
	if gin.Mode() != gin.ReleaseMode {
		Router.Use(gin.Logger())
	}

	privateGroup := Router.Group("")
	//TODO 配置项 非生产环境才启用Swagger
	docs.SwaggerInfo.BasePath = ""
	Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	blogRouter := router.RouterGroupApp.Blog
	//private Group 设置中间件
	privateGroup.Use(middleware.JWTAuth())
	//.Use(middleware.JWTAuthMiddleware())
	{
		blogRouter.InitBlogUserRouter(privateGroup)
		blogRouter.InitBlogPostRouter(privateGroup)
		blogRouter.InitBlogCommentRouter(privateGroup)
	}

	return Router
}
